package com.example.overdue.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.example.fresh.R;
import com.example.overdue.data.OberdueData;
import com.example.overdue.util.DataUtil;

import java.util.List;

//显示过期物品的类别图标的适配器
public class ImageAdapter extends BaseAdapter {

    private Context mContext;
    private List<OberdueData> mList;//数据源

    public ImageAdapter(Context context, List<OberdueData> mList) {
        this.mContext = context;
        this.mList = mList;
    }


    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;


        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.layout_grid_item, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.itemImg = (ImageView) convertView.findViewById(R.id.iv_head);

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 这里只是模拟，实际开发可能需要加载网络图片，可以使用ImageLoader这样的图片加载框架来异步加载图片
        viewHolder.itemImg.setImageResource(mList.get(position).getTypeImage());

        //把数据位置给控件，用于点击事件的时候获取
        viewHolder.itemImg.setTag(position);
        //设置图片的点击事件
        viewHolder.itemImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取数据位置
                int position = (int) v.getTag();
                String msg = "物品名称：" + mList.get(position).getTitle()
                        + "\n" + "物品类型：" + mList.get(position).getTypeStr()
                        + "\n" + "过期时间：" + DataUtil.showTime(mList.get(position).getTime());
                showNormalDialog(msg);
            }
        });

        return convertView;
    }


    private void showNormalDialog(String msg) {
        /*
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("物品详情");
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton("知道了", null);
        // 显示
        normalDialog.show();
    }


    class ViewHolder {
        ImageView itemImg;
    }
}
